import { config } from "../../api";
const debug = process.env.NODE_ENV !== "production";

const MUTATION_TYPES = {
  ROLE: "ROLE",
  SYSTEM: "SYSTEM",
  TENANT: "TENANT"
};

const state = {
  systemConfig: {},
  tenantConfig: {},
  configList: []
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.SYSTEM](state, configList) {
    state.systemConfig = Object.fromEntries(
      configList.map((item) => {
        return [
          item.configKey,
          {
            id: item.id,
            key: item.configKey,
            name: item.configDesc,
            type: item.configType
          }
        ];
      })
    );
  },
  [MUTATION_TYPES.TENANT](state, data) {
    state.tenantConfig = data.records?.[0];
  },
  [MUTATION_TYPES.ROLE](state, data) {
    state.configList = data.records;
  }
};

const actions = {
  async search({ commit }, filter) {
    let response = await config.search({ scope: "SYSTEM", filter });
    if (response?.code === 0) {
      commit(MUTATION_TYPES.SYSTEM, response.data);
      return response.data;
    }
  },
  async searchTenant({ commit }, filter) {
    let response = await config.search({ scope: "TENANT", filter });
    if (response?.code === 0) {
      commit(MUTATION_TYPES.TENANT, response.data);
      return response.data;
    }
  },
  async searchRole({ commit }, filter) {
    let response = await config.search({ scope: "ROLE", filter });
    if (response?.code === 0) {
      commit(MUTATION_TYPES.ROLE, response.data);
      return response.data;
    }
  }
};

export default {
  strict: debug,
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
